<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta name="referrer" content="no-referrer"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../../css/public.css" media="all">
    <link rel="stylesheet" href="../../lib/yzhUpload/control/css/zyUpload.css" type="text/css">
    <style>
        body {
            background-color: #ffffff;
        }

        .aui-upload-box {
            background-color: #fff;
            width: 105px;
            height: 105px;
            padding-top: 5px;
            padding-right: 5px;
        }

        .chose_pic_btn {
            width: 95px;
            height: 95px;
            position: relative;
            display: inline-block;
            background-image: url('');
            box-sizing: border-box;
            background-size: 45px 45px;
            background-position: center center;
            background-repeat: no-repeat;
            background-color: #ededed;
            margin-left: 3.3333%;
            margin-bottom: 12px;
            border-radius: 5px;
        }

        .chose_pic_btn div {
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            width: 100%;
            height: 100%;
        }

        .cancel {
            width: 20px;
            height: 20px;
            line-height: 19px;
            border: 1px solid #dbd9d9;
            background-color: #dbd9d9;
            border-radius: 50%;
            position: absolute; /* 父组件赋予属性relative生效 */
            right: 0px; /* 使元素处于右上角-右 */
            top: 0px; /* 使元素处于右上角-上 */
        }

        .cancel::before,
        .cancel::after {
            content: "";
            position: absolute;
            height: 14px;
            width: 2px;
            top: 3px; /* 使X处于圆中心 */
            left: 9px; /* 使X处于圆中心 */
            background-color: #353535;
        }

        .cancel::before {
            transform: rotate(45deg);
        }

        .cancel::after {
            transform: rotate(-45deg);
        }

        .layui-form-select dl {
            top: auto;
            bottom: 36px;
        }

        .zyupload {
            height: auto !important;
        }

        .layui-table th {
            text-align: center;
        }

        .layui-table td {
            text-align: center;
        }

        .layui-form-selectup dl {
            bottom: auto;
        }

    </style>
</head>
<body>
<div class="layui-form layuimini-form" lay-filter="enterprise-form">
    <div class="layui-form-item">
        <label class="layui-form-label required">企业编号</label>
        <div class="layui-input-block">
            <input type="text" name="enterpriseNo" readonly value="" class="layui-input" readonly>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">企业名称</label>
        <div class="layui-input-block">
            <input type="text" name="enterpriseName" lay-verify="required" placeholder="请填写企业名称" value=""
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">企业头像</label>
        <div class="layui-input-block">
            <div class="layui-upload">
                <div class="aui-upload-box">
                    <div class="aui-upload-pic">
					<span class="chose_pic_btn" id="avatarImage">
						<div>
                        </div>
					</span>
                    </div>
                </div>
                <p id="errText"></p>
                <button type="button" class="layui-btn" id="upload-avatar-image">上传图片</button>
            </div>
            <input type="text" style="display: none" name="avatar" placeholder="请输入企业头像链接"
                   value="" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">企业简介</label>
        <div class="layui-input-block">
            <div id="editor" style="margin: 0px 0 5px 0"></div>
            <button class="layui-btn layui-btn-danger" onclick="emptyDetails()">清除简介</button>
            <input type="text" name="introduction" lay-verify="required" lay-reqtext="企业简介不能为空" value=""
                   style="display:none;">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">统一社会信用代码</label>
        <div class="layui-input-block">
            <input type="text" name="organizationCode" lay-verify="required" placeholder="请填写组织机构代码" value=""
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">企业类型</label>
        <div class="layui-input-block">
            <input type="text" name="registrationType" placeholder="请填写注册类型" value="" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">所属行业</label>
        <div class="layui-input-block">
            <input type="text" name="industry" placeholder="请填写所属行业" value="" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item" id="area-picker">
        <div class="layui-form-label required">所属地区</div>
        <div class="layui-input-inline" style="width: 200px;">
            <select name="province" class="province-selector" lay-search data-value="" lay-verify="required"
                    lay-filter="province-1">
                <option value="">请选择省</option>
            </select>
        </div>
        <div class="layui-input-inline" style="width: 200px;">
            <select name="city" class="city-selector" lay-search lay-verify="required" data-value=""
                    lay-filter="city-1">
                <option value="">请选择市</option>
            </select>
        </div>
        <div class="layui-input-inline" style="width: 200px;">
            <select name="area" class="county-selector" lay-search lay-verify="required" data-value=""
                    lay-filter="county-1">
                <option value="">请选择区</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">成立日期</label>
        <div class="layui-input-block">
            <input type="text" autocomplete="off" name="establishmentDate" id="establishmentDate"
                   class="layui-input"
                   placeholder="请选择成立日期">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">注册地址</label>
        <div class="layui-input-block">
            <input type="text" name="registeredAddress" placeholder="请填写注册地址" value="" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">注册资本</label>
        <div class="layui-input-block">
            <input type="text" name="registeredCapital" placeholder="请填写注册资本" value="0" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">营业执照</label>
        <div class="layui-input-block">
            <div style="display: flex;flex-wrap: wrap">
                <div id="ad-images" style="display: flex;flex-wrap: wrap"></div>
                <div class="aui-upload-box" onclick="addBusinessLicense()">
                    <div class="aui-upload-pic">
					<span class="chose_pic_btn">
						<div></div>
					</span>
                    </div>
                </div>
            </div>
            <div id="zy-upload" class="zyupload"></div>
            <input type="text" name="businessLicense" value="" hidden>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">经营范围</label>
        <div class="layui-input-block">
            <input type="text" name="businessScope" placeholder="请填写经营范围" value="" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">法定代表人</label>
        <div class="layui-input-block">
            <input type="text" name="legalPerson" lay-verify="required" placeholder="请填写法人姓名" value=""
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">联系电话</label>
        <div class="layui-input-block">
            <input type="text" name="phoneNumber" lay-verify="required" placeholder="请填写法人联系电话" value=""
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">电子邮箱</label>
        <div class="layui-input-block">
            <input type="text" name="email" placeholder="请填写企业电子邮箱" value="" class="layui-input">
        </div>
    </div>
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
        <legend>企业管理员信息</legend>
    </fieldset>
    <div class="layui-form-item">
        <label class="layui-form-label required">管理员ID</label>
        <div class="layui-input-block">
            <input type="text" name="userId" lay-verify="required" readonly value="" class="layui-input" readonly>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">管理员昵称</label>
        <div class="layui-input-block">
            <input type="text" name="nickName" value="" class="layui-input">
        </div>
    </div>
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
        <legend>关联项目</legend>
    </fieldset>
    <div class="layui-form-item">
        <label class="layui-form-label">关联商品</label>
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-sm layui-btn associatedGoods">查看详情<span class="layui-badge layui-bg-gray"
                                                                                       id="goodsQuantity">0</span>
            </button>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">关联品牌</label>
        <div class="layui-input-block">
            <input type="text" id="brandList" name="brandList" value="" readonly class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">提交</button>
        </div>
    </div>
</div>
<script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="../../js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script src="../../lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
<script src="../../lib/common/common.js" charset="utf-8"></script>
<script src="https://unpkg.com/cos-js-sdk-v5/dist/cos-js-sdk-v5.min.js"></script>
<!-- 引用核心层插件 -->
<script type="text/javascript" src="../../lib/yzhUpload/core/zyFile.js"></script>
<!-- 引用控制层插件 -->
<script type="text/javascript" src="../../lib/yzhUpload/control/js/zyUpload.js"></script>
<script src="../../js/lay-module/xm-select-master/dist/xm-select.js" charset="utf-8"></script>
<script>
    let editor;
    let enterpriseNo;
    let userId;
    window.onload = function () {
        userId = GetQueryString("userId")
        if (isNotNull(userId)) {
            init(userId);
            $("#zy-upload").zyUpload({
                width: "650px",                 // 宽度
                height: "400px",                 // 宽度
                itemWidth: "120px",                 // 文件项的宽度
                itemHeight: "100px",                 // 文件项的高度
                url: "/upload/UploadAction",  // 上传文件的路径
                multiple: true,                    // 是否可以多个文件上传
                dragDrop: true,                    // 是否可以拖动上传文件
                del: true,                    // 是否可以删除文件
                finishDel: false,  				  // 是否在上传文件完成后删除预览
                /* 外部获得的回调接口 */
                onSelect: function (files, allFiles) {                    // 选择文件的回调方法
                    console.info("当前选择了以下文件：");
                    console.info(files);
                    console.info("之前没上传的文件：");
                    console.info(allFiles);
                },
                onDelete: function (file, surplusFiles) {                     // 删除一个文件的回调方法
                    console.info("当前删除了此文件：");
                    console.info(file);
                    console.info("当前剩余的文件：");
                    console.info(surplusFiles);
                },
                onSuccess: function (file, response) {                    // 文件上传成功的回调方法
                    console.info("此文件上传成功：");
                    if (isNotNull(response.url)) {
                        uploadAddToImg(response.url);
                    }
                },
                onFailure: function (file) {                    // 文件上传失败的回调方法
                    console.info("此文件上传失败：");
                    console.info(file);
                },
                onComplete: function (responseInfo) {           // 上传完成的回调方法
                    console.info("文件上传完成");
                    console.info(responseInfo);
                }
            });
        } else {
            layer.msg('数据异常，请重试');
            setTimeout(function () {
                let iframeIndex = parent.layer.getFrameIndex(window.name);
                parent.layer.close(iframeIndex);
            }, 1500);
        }
    }

    function generateUniqueID(length) {
        // 获取当前时间戳并转换成字符串
        const timestamp = Date.now().toString();
        // 数字数组
        const str_arr = [...Array(10).keys()].map(num => num.toString());
        // 生成指定长度的随机数字符串
        const str = Array.from({length: length - 13}, () => str_arr[Math.floor(Math.random() * str_arr.length)]).join("");
        // 将随机数字符串和时间戳合并成结果字符串
        const res_str = "EP" + str + timestamp;
        // 返回生成的带前缀的唯一ID
        return res_str;
    }


    layui.use(['layer', 'form'], function () {
        const form = layui.form,
            layer = layui.layer,
            $ = layui.$,
            upload = layui.upload,
            laydate = layui.laydate;

        //常规使用 - 普通图片上传
        let uploadInst = upload.render({
            elem: '#upload-avatar-image'
            , url: '/meily/upload'
            , before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#avatarImage').css({
                        'background-image': 'url(' + result + ')',
                        'background-size': '100% 100%'
                    }); //图片链接（base64）
                });
                layer.msg('上传中', {icon: 16, time: 0});
            }
            , done: function (res) {
                //如果上传失败
                if (res.code !== '200') {
                    return layer.msg('上传失败');
                }
                //上传成功的一些操作
                $('input[name="avatar"]').val(res.url);
                $('#errText').html(''); //置空上传失败的状态
            }
            , error: function () {
                //演示失败状态，并实现重传
                var demoText = $('#errText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs upload-reload">重试</a>');
                demoText.find('.upload-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
            //进度条
            , progress: function (n, elem, e) {
                if (n == 100) {
                    layer.msg('上传完毕', {icon: 1});
                }
            }
        });

        // 初始化日期选择器
        laydate.render({
            elem: '#establishmentDate',
            type: 'date', //选择器类型，只显示年月
            format: 'yyyy-MM-dd', //日期格式
            max: 'now',
        });

        //监听提交
        form.on('submit(saveBtn)', function (data) {
            let index = layer.alert("确定提交吗？", {
                title: '提示'
            }, function () {
                let myMsg = layer.msg("正在提交...", {
                    icon: 16,
                    time: -1
                })
                $.ajax({
                    type: "post",
                    url: '/enterprise/edit',
                    data: JSON.stringify(data.field),
                    dataType: 'json',
                    contentType: 'application/json; charset=UTF-8',
                    success: function (req) {
                        if (req.code === '200') {
                            layer.msg("操作成功");
                            layer.close(index);
                            // 关闭弹出层
                            setTimeout(function () {
                                layer.close(myMsg);//手动关闭
                                let iframeIndex = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(iframeIndex);
                                // 调用父页面的方法
                                let parentWindow = window.parent;
                                parentWindow.reloadTable();
                            }, 1500);
                        } else {
                            layer.msg(req.msg);
                        }

                    },
                    error: function (e) {
                        layer.msg("操作失败");
                        layer.close(myMsg);//手动关闭
                    }
                })

            });
            return false;
        });

        $('.associatedGoods').click(function () {
            let parentWindow = window.parent;
            parentWindow.layer.open({
                title: '关联商品',
                type: 2,
                shade: 0.2,
                maxmin: true,
                shadeClose: true,
                area: ['100%', '100%'],
                content: `./associatedItems/goods-item.html?enterpriseNo=${enterpriseNo}`,
                end: function () {
                    //关闭弹框后触发
                    getRelevancyItemsInfo();
                }
            });
        });
    });

    function addBusinessLicense() {
        layui.use(['layer', 'form'], function () {
            const layer = layui.layer
            layer.prompt({
                title: '请输入图片链接',
                btn: ['确定', '取消'],
                area: ['200px', '20px'],
                formType: 0
            }, function (text, index) {
                const input = text.trim();
                if (input) {
                    let images = $('input[name="businessLicense"]').val();
                    const newImages = images ? `${images},${input}` : input;
                    $('input[name="businessLicense"]').val(newImages);
                    renderImages(newImages);
                } else {
                    layer.msg("图片链接不能为空噢");
                }
                layer.close(index);
            });
        });
    }

    /**
     * 渲染加载的图片
     */
    function renderImages(imageLinks) {
        const adImages = $("#ad-images");  // 缓存目标元素
        adImages.empty();  // 清空目标元素
        if (!imageLinks) return;  // 如果参数为空或undefined则直接返回
        const imgsArr = imageLinks.split(",");  // 将参数字符串分割成图片链接数组
        const html = imgsArr.map((link, index) => {  // 构建HTML代码
            const div = $("<div>").css({  // 创建div元素并设置样式和属性
                padding: "5px 10px 15px 0px",
                position: "relative",
                width: "95px",
                height: "95px"
            });
            const img = $("<img>").attr({  // 创建img元素并设置样式和属性
                width: "95px",
                height: "95px",
                src: link
            });
            const span = $("<span>").addClass("cancel").on("click", () => delImage(index));  // 创建span元素并设置样式和事件处理器
            return div.append(img).append(span);  // 将img和span添加到div中并返回div元素
        });  // 将jQuery对象转换成DOM元素数组
        adImages.html(html);  // 将HTML代码添加到目标元素中
    }

    /**
     * 删除图片
     */
    function delImage(index) {
        const businessLicenseInput = $('input[name="businessLicense"]');  // 缓存目标输入框
        let imageLinks = businessLicenseInput.val();  // 获取目标输入框的值
        if (!imageLinks) return;  // 如果目标输入框的值为空，则直接返回
        const imgsArr = imageLinks.split(",");  // 将图片链接字符串分割成数组
        const newImageLinks = imgsArr.filter((link, i) => i !== index).join(",");  // 过滤掉指定下标的图片链接并拼接成新的图片链接字符串
        businessLicenseInput.val(newImageLinks);  // 将新的图片链接字符串设置为目标输入框的值
        renderImages(newImageLinks);  // 重新生成图片预览
    }

    /**
     * 上传文件完成后将文件地址添加到图片列表中
     * @param url
     */
    function uploadAddToImg(url) {
        const businessLicenseInput = $('input[name="businessLicense"]'); // 缓存目标输入框
        let images = businessLicenseInput.val() ?? ''; // 获取目标输入框的值
        if (isNotNull(url)) {
            images = `${images ? images + ',' : ''}${url}`; // 使用模板字符串简化字符串的拼接
            businessLicenseInput.val(images); // 将新的图片链接字符串设置为目标输入框的值
            renderImages(images); // 重新生成图片预览
        }
    }

    //富文本编辑器
    layui.use(['layer', 'wangEditor'], function () {
        var $ = layui.jquery,
            layer = layui.layer,
            wangEditor = layui.wangEditor;

        editor = new wangEditor('#editor');
        editor.customConfig.uploadImgServer = "/meily/upload";
        editor.customConfig.uploadFileName = 'file';
        editor.customConfig.pasteFilterStyle = false;
        editor.customConfig.uploadImgMaxLength = 5;
        editor.customConfig.uploadImgHooks = {
            // 上传超时
            timeout: function (xhr, editor) {
                layer.msg('上传超时！')
            },
            // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
            customInsert: function (insertImg, result, editor) {
                console.log(result);
                if (result.code == 200) {
                    var url = result.url;
                    insertImg(url);
                    // url.forEach(function (e) {
                    //     insertImg(e);
                    // })
                } else {
                    layer.msg(result.msg);
                }
            }
        };
        editor.customConfig.customAlert = function (info) {
            layer.msg(info);
        };
        editor.customConfig.onchange = function (html) {
            $('input[name="introduction"]').val(html);
        };
        editor.create();
    });

    /**
     * 清空富文本编辑器
     */
    function emptyDetails() {
        editor.txt.clear();
        $('input[name="introduction"]').val('');
        layui.use(['layer'], function () {
            let $ = layui.$, layer = layui.layer;
            layer.msg("已清除！")
        })
    }

    layui.use(['form', 'layarea'], function () {
        let layarea = layui.layarea;
        layarea.render({
            elem: '#area-picker',
        });
    })

    function init(userId) {
        $.ajax({
            type: "get",
            url: '/enterprise/basic/info/' + userId,
            dataType: 'json',
            contentType: 'application/x-www-form-urlencoded',
            success: function (req) {
                layui.use(['form'], function () {
                    let form = layui.form,
                        $ = layui.$,
                        layarea = layui.layarea;

                    form.val('enterprise-form', {
                        "userId": req.data.userId,
                        "enterpriseNo": req.data.enterpriseNo,
                        "enterpriseName": req.data.enterpriseName,
                        "legalPerson": req.data.legalPerson,
                        "phoneNumber": req.data.phoneNumber,
                        "registrationType": req.data.registrationType,
                        "organizationCode": req.data.organizationCode,
                        "businessScope": req.data.businessScope,
                        "industry": req.data.industry,
                        "businessLicense": req.data.businessLicense,
                        "transferCode": req.data.transferCode,
                        "transferStatus": req.data.transferStatus,
                        "avatar": req.data.avatar,
                        "introduction": req.data.introduction,
                        "province": req.data.province,
                        "city": req.data.city,
                        "area": req.data.area,
                        "establishmentDate": req.data.establishmentDate,
                        "registeredAddress": req.data.registeredAddress,
                        "registeredCapital": req.data.registeredCapital,
                        "email": req.data.email,
                        "nickName": isNotNull(req.data.nickName) ? req.data.nickName : req.data.enterpriseName
                    });
                    enterpriseNo = req.data.enterpriseNo;
                    // 初始化省市信息
                    layarea.render({
                        elem: '#area-picker',
                        data: {
                            province: req.data.province,
                            city: req.data.city,
                            county: req.data.area,
                        }
                    });
                    if (isNotNull(req.data.businessLicense)) {
                        renderImages(req.data.businessLicense);
                    }
                    if (isNotNull(req.data.introduction)) {
                        initEditor(req.data.introduction);
                    }
                    if (isNotNull(req.data.avatar)) {
                        $('#avatarImage').css({
                            'background-image': 'url(' + req.data.avatar + ')',
                            'background-size': '100% 100%'
                        }); //图片链接（base64）
                    }
                    getRelevancyItemsInfo();
                })
            },
            error: function (e) {
                layer.msg("数据有误");
            }
        })
    }

    function getRelevancyItemsInfo() {
        $.ajax({
            type: "get",
            url: `/enterprise/relevancy/items/${userId}/info`,
            dataType: 'json',
            contentType: 'application/x-www-form-urlencoded',
            success: function (req) {
                if (req.code === '200') {
                    layui.use(['form'], function () {
                        let form = layui.form,
                            $ = layui.$;
                        let RelevancyItemQuantityDto = req.data;
                        if (RelevancyItemQuantityDto) {
                            const myMap = new Map(Object.entries(RelevancyItemQuantityDto));
                            // 更新统计数据
                            myMap.forEach((value, key) => {
                                if (key === "brandQuantity") {
                                    let brandQuantity = parseInt(value)
                                    if (brandQuantity > 0) {
                                        let brandListStr = '';
                                        RelevancyItemQuantityDto.brandList.forEach(item => {
                                            if (isNotNull(brandListStr)) {
                                                brandListStr += ',' + item;
                                            } else {
                                                brandListStr = item;
                                            }
                                        })
                                        $('#brandList').val(brandListStr)
                                    }
                                }
                                let id = '#' + key
                                $(id).text(value);
                            });
                        }
                    })
                }
            },
            error: function (e) {
                layer.msg("数据有误");
            }
        })
    }

    /**
     * 初始化富文本编辑器
     */
    function initEditor(html) {
        editor.txt.html(html);
    }

</script>
</body>
</html>
